# 定义组件
app1 = new Vue
  el:"#app1"
  # 变量声明
  data: 
    # 是否加载完成
    loadedSucc: false
    # 加载失败提示语
    loadedFail: ''

    # 选项卡样式
    tab_active_idx: 0
    # 显示组件
    showComp: false
    # 字典列表
    dictList: []
    # 字典查询
    dictQuery: {}
    # 字典详情
    # dictDetail: defDict

    # 当前页号
    pageNum: 1
    # 每页记录数
    pageSize: 10
    # 总页数
    pageCount: 1
    # 总记录数
    count: 0
    # 更多按钮文本
    viewMoreText: '查看更多'

    # 对话框选项
    dlgOpt: {state: false}
    # 表单提示条
    formTipsOpt: {}
    # 对话框选项
    dlgOpt: {state: false}
    # 树形选项
    treeOpt: {state: false}
    # 放大镜选项
    zoomOpt: {state: false}
    # 文件上传选项
    uploadOpt: {state: false}
    # 组件数据
    compDatas: {}
    # 下拉框数据
    comboBoxDatas: {}

    # 展示放大镜
    showZoom: false
    # 展示树目录
    showTree: false
    # 展示文件上传
    showUpload: false

    # 编辑器ID数组
    editorIdArray: []

    # 区分搜索数据列表和全部字典管理列表，false是全部字典管理列表，true是搜索列表
    isSearchDict: false

  # 组件模板
  # template: require 'mods/dict/dict_tpl.js'

  # 组件方法
  methods:

    # 弹出错误提示
    alertTipError: (content) ->
      self = @
      self.alertTip 'error', content
      return false

    # 弹出成功提示
    alertTipSuccess: (content) ->
      self = @
      self.alertTip 'success', content
      return false

    # 弹出提示
    alertTip: (tip_type, content) ->
      self = @
      # 工具条提示
      formTipsObj =
        state: true
        auto_close: true
        tip_type: tip_type
        content: content
      self.formTipsOpt = Vue.util.extend {}, formTipsObj

    # 错误处理
    errorHandler: (err) ->
      self = @
      if 403 is err?.status
        self.$router.push {path: '/login'}
        return false
      self.alertTipError err?.data?.rejects?[0]?.error or err?.data?.error or err?.message or err

    # 设置字典列表
    setDictList: (res) ->
      self = @

      tmpRes = res?.data
      tmpData = tmpRes?.data or []
      self.viewMoreText = '查看更多'

      # 设置数据列表
      # if 0 is self.dictList?.length
      #   if 0 isnt tmpData?.length
      #     if res?.body?.pageNum >= res?.body?.pageCount
      #       self.viewMoreText = '已显示全部内容'
      #     self.dictList = tmpData
      #   else
      #     self.viewMoreText = '已显示全部内容'
      # else
      #   if (0 isnt tmpData?.length) and (self?.pageNum <= self?.pageCount)

      #     if res?.body?.pageNum >= res?.body?.pageCount
      #       self.viewMoreText = '已显示全部内容'
      #     for prod in tmpData
      #       self.dictList.push prod
      #   else
      #     self.viewMoreText = '已显示全部内容'

      # 设置分页参数
      self.pageNum = tmpRes?.pageNum or 1
      self.pageCount = tmpRes?.pageCount or 1
      self.count = tmpRes.count or 1
      self.pageSize = tmpRes.pageSize or 10

      # 控制当前页不能大于最大页码
      if self.pageNum > self.pageCount
        self.pageNum = self.pageCount

    # 设置模糊搜索字典列表
    setSearchDictList: (res) ->
      self = @

      tmpRes = res?.body[0]
      tmpData = tmpRes?.data or []
      self.viewMoreText = '查看更多'

      # 设置数据列表
      if 0 is self.dictList?.length
        if 0 isnt tmpData?.length

          if res?.body[0]?.pageNum >= res?.body[0]?.pageCount
            self.viewMoreText = '已显示全部内容'
          self.dictList = tmpData
        else
          self.viewMoreText = '已显示全部内容'
      else
        if (0 isnt tmpData?.length) and (self?.pageNum <= self?.pageCount)

          if res?.body[0]?.pageNum >= res?.body[0]?.pageCount
            self.viewMoreText = '已显示全部内容'
          for prod in tmpData
            self.dictList.push prod
        else
          self.viewMoreText = '已显示全部内容'

      # 设置分页参数
      self.pageNum = tmpRes?.pageNum or 1
      self.pageCount = tmpRes?.pageCount or 1
      self.count = tmpRes.count or 1
      self.pageSize = tmpRes.pageSize or 10

    # 查询字典列表 - 分页
    getDictList: (page) ->
      self = @
      # 动态设置页码
      self.pageNum = page or 1
      if 1 isnt self.pageNum
        self.viewMoreText = '正在拉取数据……'

      # 查询参数
      params =
        pageNum: self.pageNum
        pageSize: self.pageSize
        query:
          dict_id: self.dictQuery?.dict_id
          dict_name: self.dictQuery?.dict_name
          # dept_id: self.dictQuery?.dept_id
          # aihao: self.dictQuery?.aihao
          # dict_res: self.dictQuery?.dict_res
      # 查询请求
      # return dict_api.getDict params
      url  = "http://localhost:8091/dict_query"

      return self.$http.post url,params
        .then (res) ->
          self.setDictList res
          return true
        .catch (err) ->
          return err

    # 模糊查询字典列表 - 分页
    getSearchDictList: (page) ->
      self = @

      # 动态设置页码
      self.pageNum = page or 1
      if 1 isnt self.pageNum
        self.viewMoreText = '正在拉取数据……'

      # 查询参数
      params =
        pageNum: self.pageNum
        pageSize: self.pageSize
        dict_id: self.dictQuery?.dict_id or ""
        dict_name: self.dictQuery?.dict_name or ""
        dept_id: self.dictQuery?.dept_id
        dict_res: self.dictQuery?.dict_res

      # 查询请求
      return dict_api.getSearchDict params
        .then (res) ->
          self.setSearchDictList res
          return true
        .catch (err) ->
          return err

    # 查询字典
    onSearchDict: (evt) ->
      self = @

      # 隐藏字典管理模糊搜索列表
      self.isSearchDict = false

      self.dictList = []
      self.getDictList 1
        .then (res) ->
          self.tab_active_idx = 1
        .catch (err) ->
          self.errorHandler err
      return

    # 模糊查询字典
    onSearchDictList: (evt) ->
      self = @

      # 显示字典管理模糊搜索列表
      self.isSearchDict = true

      self.dictList = []
      self.getSearchDictList 1
        .then (res) ->
          self.tab_active_idx = 1
        .catch (err) ->
          self.errorHandler err
      return

    # 重置查询
    onReset: ()->
      self = @
      self.dictQuery = {}
      self.dictList = []
      self.getSearchDictList 1
        .then (res) ->
          self.tab_active_idx = 1
        .catch (err) ->
          self.errorHandler err
      return

    # 字典编辑
    onEditDict: (dict) ->
      self = @
      self.loadCompDatas().then ->
        # 切换到第三个选项卡
        self.tab_active_idx = 2
        # 设置字典详情
        self.dictDetail = dict
        # DOM渲染之后加载富文本
        self.$nextTick () ->
          self.loadRichEditor()
        return
      return

    # 设置加载参数
    setLoadedParams: () ->
      self = @
      # 默认显示列表
      self.tab_active_idx = 1
      # 清空已有值
      self.dictDetail = Vue.util.extend({}, defDict)
      # 关闭编辑页面组件
      self.showComp = false

    # 设置下拉框返回值
    setComboBoxValue: (apiUrlData, text_field_name, value_field_name) ->
      cv = []
      if !!apiUrlData
        for a in apiUrlData
          o = {}
          o['text'] = a[text_field_name]
          o['value'] = a[value_field_name]
          cv.push o
      return cv

    # 加载下拉框组件数据
    loadComboBoxDatas: (compDatas) ->
      self = @
      if _.isEmpty compDatas
        return false

      # 设置组件数据
      self.compDatas = compDatas

      # 有接口地址的下拉框
      apiUrlItems = {}
      for k, v of compDatas
        # 下拉框
        if '1' is  '' + v?.comp_type
          # 无接口地址，且配置了列表项的下拉框
          if (not v?.api_url) and (0 isnt (v?.comp_items?.length or 0))
            self.comboBoxDatas[k] = v?.comp_items
          # 有接口地址
          else
            apiUrlItems[k] = v

      if not _.isEmpty(apiUrlItems)
        funcs = []
        _.map apiUrlItems, (v, k) ->
          # 请求下拉框的内容
          p = base_api.postRequestByParams v?.api_url, v?.api_query_params
            .then (res) ->
              o = {}
              text_field_name = v?.combobox?.text_field_name
              value_field_name = v?.combobox?.value_field_name
              o[k] =  self.setComboBoxValue res?.data?.data, text_field_name, value_field_name
              return o
          funcs.push p

        # 并行请求
        return Promise.all funcs
          .then (res) ->
            if 0 isnt res?.length
              for o in res
                for k, v of o
                  self.comboBoxDatas[k] = v
          .catch (err) ->
            return err
      else
        return Promise.resolve 1

    # 设置富文本返回值
    setRichEditorValue: (txtObj) ->
      self = @
      # 编辑选项卡
      if '2' is '' + self.tab_active_idx
        self.dictDetail?[txtObj?.field_name] = txtObj?.field_value
      # 查询选项卡
      else if '0' is '' + self.tab_active_idx
        self.dictQuery?[txtObj?.field_name] = txtObj?.field_value
      return

    # 加载富文本数据
    loadRichEditor: () ->
      self = @
      if 0 isnt (self.editorIdArray?.length or 0)
        for editorId in self.editorIdArray
          editorOpt = {}
          editorOpt.editor_id = editorId
          editorOpt.txt_change = (txtObj) ->
            # 设置富文本返回值
            self.setRichEditorValue txtObj
          # 根据配置项渲染富文本
          renderRichEditor editorOpt
      return

    # 加载页面组件数据
    loadCompDatas: () ->
      self = @
      return Promise.resolve 1
        .then ->
          return dict_api.getCompDatas {comp_ids: [12, 13, 14]}
        .then (res) ->
          return self.loadComboBoxDatas res?.data
        .catch (err) ->
          self.errorHandler err

    # 关闭放大镜
    closeZoom: () ->
      self = @
      self.showComp = false
      self.showZoom = false
      return

    # 打开放大镜
    openZoom: () ->
      self = @
      self.showComp = true
      self.showZoom = true
      return

    # 关闭树目录
    closeTree: () ->
      self = @
      self.showComp = false
      self.showTree = false
      return

    # 打开树目录
    openTree: () ->
      self = @
      self.showComp = true
      self.showTree = true
      return

    # 关闭文件上传
    closeUpload: () ->
      self = @
      self.showComp = false
      self.showUpload = false
      return

    # 打开文件上传
    openUpload: () ->
      self = @
      self.showComp = true
      self.showUpload = true
      return

    # 设置放大镜配置参数
    setZoomCfg: (zoomData) ->
      self = @
      # 字段值由字符串转数组
      for key in ['query_fields', 'table_fields']
        if !!zoomData?[key]
          for k, v of zoomData?[key]
            zoomData?[key]?[k] = _.split v, ','

      # 字段英文名
      elen  =  zoomData?.query_fields?.field_en_name?.length or 0
      # 字段默认值
      vLen = zoomData?.query_fields?.field_value?.length or 0

      # 设置字段默认值
      if 0 isnt elen
        if 0 is vLen
          zoomData?.query_fields?.field_value = []
        for idx in [0...elen]
          zoomData?.query_fields?.field_value?[idx] = ''

      # 返回配置参数
      return zoomData

    # 设置放大镜返回值
    setZoomValue: (field_key, field_name, compData, checkedItems) ->
      self = @
      # 放大镜返回文本
      text_field_name = compData?.zoom?.text_field_name
      # 放大镜返回值
      value_field_name = compData?.zoom?.value_field_name

      # 编辑选项卡
      if '2' is '' + self.tab_active_idx
        self.dictDetail['' + field_name] = checkedItems?[0]?['' + text_field_name]
        self.dictDetail['' + field_key] = checkedItems?[0]?['' +  value_field_name]
        return

      # 查询选项卡
      else if '0' is '' + self.tab_active_idx
        self.dictQuery['' + field_name] = checkedItems?[0]?['' + text_field_name]
        self.dictQuery['' + field_key] = checkedItems?[0]?['' +  value_field_name]
        return
      return

    # 设置树目录返回值
    setTreeValue: (field_key, field_name, compData, checkedItems) ->
      self = @
      # 树目录返回文本
      node_field = compData?.tree.node_field
      # 树目录返回值
      node_id_field = compData?.tree?.node_id_field

      # 编辑选项卡
      if '2' is '' + self.tab_active_idx
        self.dictDetail['' + field_key] = checkedItems?[0]?['' + node_id_field]
        self.dictDetail['' + field_name] = checkedItems?[0]?['' + node_field]
        return

      # 查询选项卡
      else if '0' is '' + self.tab_active_idx
        self.dictQuery['' + field_key] = checkedItems?[0]?['' + node_id_field]
        self.dictQuery['' + field_name] = checkedItems?[0]?['' + node_field]
        return
      return

    # 下拉框触发
    onSelectChange: (evt, name) ->
      self = @
      obj = evt.target
      text = evt?.target?.options?[obj?.selectedIndex]?.text or ''
      self.dictDetail['' + name] = text
      return

    # 选择放大镜触发
    onSelectZoom: (comp_id, field_key, field_name) ->
      self = @
      # 组件配置项
      compData = self.compDatas?[comp_id]
      # 若无内容，则中断执行
      return false if not compData
      # 整理放大镜配置参数
      zoomData = self.setZoomCfg compData?.zoom
      # 接口地址
      if !!compData?.api_url
        # 放大镜选项
        zoomObj =
          state: true
          api_url: compData?.api_url
          ok: (checkedItems) ->
            self.closeZoom()
            self.setZoomValue field_key, field_name, compData, checkedItems
            return
          cancel: () ->
            self.closeZoom()
            return
        # 打开放大镜
        self.zoomOpt = Vue.util.extend zoomObj, zoomData
        self.openZoom()
        return
      return

    # 选择树形目录触发
    onSelectTree: (comp_id, field_key, field_name) ->
      self = @
      # 组件配置项
      compData = self.compDatas?[comp_id]
      # 若无内容，则中断执行
      return false if not compData
      # 接口地址
      if !!compData?.api_url
        # 树形选项
        treeObj =
          state: true
          comp_data: compData
          ok: (checkedItems) ->
            self.closeTree()
            self.setTreeValue field_key, field_name, compData, checkedItems
            return
          cancel: () ->
            self.closeTree()
            return
        # 打开树目录
        self.treeOpt = Vue.util.extend {}, treeObj
        self.openTree()
        return
      return

    # 选择文件上传
    onSelectFile: (comp_id, field_key, field_name) ->
      self = @
      # 组件配置项
      compData = self.compDatas?[comp_id]
      # 若无内容，则中断执行
      return false if not compData
      # 上传对象
      uploadObj =
        comp_data: compData
        state:true
        # 上传点击确定事件
        ok:(files)->
          self.dictDetail[''+field_key] = ''
          for file, index in files
            if index < files?.length-1
              self.dictDetail[''+field_key] += file[0]?.file_url+','
            else
              self.dictDetail[''+field_key] += file[0]?.file_url
          self.closeUpload()
        # 上传点击取消事件
        cancel:()->
          self.closeUpload()

      self.uploadOpt = Vue.util.extend {}, uploadObj
      # 打开文件上传
      self.openUpload()
      return

    # 新增字典
    onAddDict: () ->
      self = @
      self.closeComp()
      self.loadCompDatas().then ->
        self.setLoadedParams()
        self.tab_active_idx = 2
        delete self.dictDetail._id
        # DOM渲染之后加载富文本
        self.$nextTick () ->
          self.loadRichEditor()
        return
      return

    # 添加字典项
    onAddDictItem: (evt) ->
      self = @
      if self.dictDetail?.dict_items
        self.dictDetail?.dict_items.push Vue.util.extend({}, {text: '', value: ''})
      return

    # 删除字典项
    onRemoveDictItem: (evt, idx) ->
      self = @
      if 0 isnt self.dictDetail?.dict_items?.length
        self.dictDetail.dict_items.splice idx, 1
      return

    # 删除字典
    onRemoveResouce: (dict_id) ->
      self = @
      if dict_id
        dict_ids = ("" + dict_id).split ','

      # 工具条提示
      dlgTipsObj =
        state: true
        title: '删除提示'
        content: '您确定删除吗?'
        msg_type: 'confirm'
        # 弹出框点击确定事件
        ok: () ->
          dict_api.removeDict {dict_ids: dict_ids}
            .then (res) ->
              # 隐藏弹出框
              self.dlgOpt.state = false
              self.dictList = []
              self.loadData()
            .catch (err) ->
              self.errorHandler err
        # 弹出框点击取消事件
        cancel: () ->
          # 隐藏弹出框
          self.dlgOpt.state = false

      self.dlgOpt = Vue.util.extend {}, dlgTipsObj

    # 选项卡点击切换
    tabsToggle: (active_idx) ->
      self = @
      self.closeComp()
      self.tab_active_idx = active_idx
      if 1 isnt active_idx
        self.loadCompDatas().then ->
        # DOM渲染之后加载富文本
        self.$nextTick () ->
          self.loadRichEditor()
        return

    # 关闭组件
    closeComp: () ->
      self = @
      # 显示表单
      self.showComp = false
      # 关闭放大镜
      self.showZoom = false
      # 关闭树组件
      self.showTree = false
      # 关闭上传组件
      self.showUpload = false
      return

    # 保存字典
    onSaveDict: () ->
      self = @
      # 保存参数
      params =
        dict: self.dictDetail

      # 执行请求链
      Promise.resolve true
        .then ->
          # 保存字典
          dict_api.saveDict params
        .then (res) ->
          self.dictList = []
          self.loadData()
        .catch (err) ->
          self.errorHandler err

    # 依赖组件
    # components:
    #   'c-form-tips': require 'mods/form_tips/form_tips_mod'
    #   'c-dialog': require 'mods/dialog/dialog_mod'
    #   'c-zoom': require 'mods/zoom/zoom_mod'
    #   'c-select-tree': require 'mods/tree_select/tree_select_mod'

    # 加载成功
    loadedSuccFunc: () ->
      self = @
      self.$nextTick () ->
        setTimeout () ->
          # 加载成功标识
          self.loadedSucc = true
        , 500

    # 数据加载
    loadData: () ->
      self = @
      # 设置加载参数
      # self.setLoadedParams()
      # 执行请求链
      Promise.resolve true
        .then ->
          # 查询字典列表 - 路由切换时查询
          return self.getDictList 1
        .then (res) ->
          # 加载成功执行
          self.loadedSuccFunc()
        .catch (err) ->
          # 错误处理
          self.errorHandler err

  # 路由切换时销毁滚动组件
  beforeRouteLeave: (to, from, next) ->
    self = @
    return next true

  # 计算属性
  computed:
    # 加载中的样式
    loaddingClass: () ->
      self = @
      if self.loadedSucc
        return 'c-hidden'
      if self.loadedFail
        return 'c-hidden'
      return''

    # 加载成功的样式
    loadedSuccClass: () ->
      self = @
      return if self.loadedSucc then '' else 'c-vhidden'

    # 加载失败的样式
    loadedFailClass: () ->
      self = @
      return if self.loadedFail then '' else 'c-hidden'

  # 组件初始化执行
  mounted: () ->
    self = @
    self.loadData()
    # self.loadedSuccFunc()